package com.service.Impl;

import java.util.ArrayList;
import java.util.concurrent.Future;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dao.UserDao;
import com.entity.User;
import com.service.AsyncService;
@Service
public class AsyncServiceImpl implements AsyncService {
	
	private static Logger log = Logger.getLogger(AsyncServiceImpl.class);
	
	@Resource
	private UserDao userDao;
	
	/**
	 * 异步有返回
	 */
	@Async  
	public Future<ArrayList<String>> asyncMethodWithReturnType(int no) {  
	    System.out.println("Execute method asynchronously - " + Thread.currentThread().getName());  
	    try {  
	    	ArrayList<String> arrayList = new ArrayList<String>();
	    	arrayList.add("list"+no);
	        Thread.sleep(5000);  
	        return new AsyncResult<ArrayList<String>>(arrayList);  
	    } catch (InterruptedException e) {  
	        //  
	    }  
	   
	    return null;  
	}
	
	/**
	 * 异步无返回
	 */
	@Async  
	public void asyncMethodWithVoidReturnType(int no) {  
	    System.out.println("Execute method asynchronously. " + Thread.currentThread().getName());
	    try {
	        Thread.sleep(5000);
	    } catch (InterruptedException e) {
	    	
	    }
	}
	
	/**
	 * 异步事务
	 */
	@Async
	@Transactional
	public void syncUnit(int no) {
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		User user = new User();
		user.setUsername("user");
		user.setPassword("123456");
		user.setAge(1);
		user.setDept_id(1);
		user.setName("user");
		user.setStatus(1);
		user.setId(1);
		userDao.add(user);
		int i=0/0;
		user = new User();
		user.setUsername("user");
		user.setPassword("123456");
		user.setAge(1);
		user.setDept_id(1);
		user.setName("user");
		user.setStatus(1);
		user.setId(1);
		userDao.add(user);
	}

}